package editor.UI
{
	import flash.display.Sprite;
	import flash.events.Event;
	import starling.core.Starling;
	
	/**
	 * @author Kirill Pletnev
	 */
	public class EditorUI extends Sprite
	{
		private static var _instanse:EditorUI = new EditorUI();
		
		private var _topPanel:TopEditorPanel;
		private var _rightPanel:RightEditorPanel;
		private var _newTileWindow:NewTileWindow;
		
		public function EditorUI()
		{
			if (_instanse != null)
			{
				throw new Error("ConfigurationManager instance already existing in Singleton");
			}
		}
		
		public function init():void
		{
			_topPanel = new TopEditorPanel();
			_topPanel.init();
			addChild(_topPanel);
			
			_rightPanel = new RightEditorPanel();
			_rightPanel.y = _topPanel.bg.height;
			_rightPanel.init();
			addChild(_rightPanel);
			
			_topPanel.addEventListener(TopEditorPanel.OPEN_NEW_TILE_WINDOW, openNewTileWindow)
			
			Starling.current.nativeOverlay.addChild(this);
		}
		
		private function openNewTileWindow(event:Event):void
		{
			if (_newTileWindow == null)
			{
				_newTileWindow = new NewTileWindow();
				_newTileWindow.create();
				_newTileWindow.addEventListener(NewTileWindow.CREATE_TILE_EVENT, onCreateTile);
				_newTileWindow.addEventListener(NewTileWindow.CLOSE_WINDOW_EVENT, onCloseNewTileWindow);
			}
		}
		
		private function onCloseNewTileWindow(event:Event):void
		{
			disposeNewTileWindow();
		}
		
		private function onCreateTile(event:Event):void
		{
			_rightPanel.updateTilesContent();
			
			disposeNewTileWindow();
		}
		
		private function disposeNewTileWindow():void
		{
			_newTileWindow.removeEventListener(NewTileWindow.CREATE_TILE_EVENT, onCreateTile);
			_newTileWindow.removeEventListener(NewTileWindow.CLOSE_WINDOW_EVENT, onCloseNewTileWindow);
			_newTileWindow.dispose();
			_newTileWindow = null;
		}
		
		public static function get instanse():EditorUI
		{
			return _instanse;
		}
		
		public function get topPanel():TopEditorPanel 
		{
			return _topPanel;
		}
		
		public function get newTileWindow():NewTileWindow 
		{
			return _newTileWindow;
		}
		
		public function get rightPanel():RightEditorPanel 
		{
			return _rightPanel;
		}
	}
}